import React, { useState, useEffect } from 'react';
import { LoadingOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { history } from 'umi';
import { Form, Card, Button, Space, Input, Row, Col, Upload, message, Modal } from 'antd'
import styles from './index.less'
import { getSettingsInfo, updateSettingsInfo, uploadFile } from '@/services/common'

const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 17 },
};
const { confirm } = Modal;
const SysSettings: React.FC = () => {
    const [info, setInfo] = useState<COMMON_API.Settings | undefined>(undefined)
    const [loading, setLoading] = useState<boolean>(false)
    const [logoUrl, setLogoUrl] = useState<string>('')
    const [logoAllUrl, setLogoAllUrl] = useState<string>('')

    const uploadButton = (
        <div>
          {loading ? <LoadingOutlined /> : <PlusOutlined />}
          <div style={{ marginTop: 8 }}>上传LOGO</div>
        </div>
      );

    useEffect(() => { 
     const fetchSettings = async () => {
        const rsp = await getSettingsInfo()
        if(rsp.code === 0) {
          setInfo(rsp.data)
          setLogoUrl(rsp.data.logo)
          setLogoAllUrl(rsp.data.logo && rsp.data.logo.startsWith('http') ? rsp.data.logo : window.location.protocol + '//' + window.location.host + ':7001' + rsp.data.logo)
        }
     }
      fetchSettings()
    }, [])
    
    const onFinish = (values: any) => {
        confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined />,
            content: '是否确认保存系统配置信息? ',
            onOk: async () => {
                const rsp = await updateSettingsInfo({...values, logo: logoUrl})
                if(rsp.code === 0) {
                  confirm({
                      title: '提示',
                      icon: <ExclamationCircleOutlined />,
                      content: '系统配置修改成功, 是否确认刷新应用',
                      onOk: () => {
                          window.location.reload();
                      }
                    })
                }  
             }
          })
    };

    const beforeUpload = (file: any) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('只能上传 JPG/PNG 格式的图片!');
        }
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
            message.error('图片大小必须小于5MB!');
        }
        return isJpgOrPng && isLt5M;
    }

    const customRequest = async (data: any) => {
        setLoading(true) 
        const formData = new FormData()
        formData.append('file', data.file)
        const params = { single: 1, category: 'logo'}
        const rsp = await uploadFile(params, formData)
        if(rsp.code === 0) {
            setLogoUrl(rsp.data.path)
            setLogoAllUrl(window.location.protocol + '//' + window.location.host + ':7001' + rsp.data.path)
        }
        setLoading(false) 
    }

    const closeBox = () => {
        history.push('/')
    }

    return (
        <Card className={styles.card}>
            <Row gutter={16}>
                <Col span={16}> 
                <Row style={{marginBottom: '17px'}}>
                    <Col span={6}>
                        <div className={styles.logoLabel}>系统Logo&nbsp;:</div> 
                     </Col>
                      <Col span={17}>
                       <Upload
                            name="avatar"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            customRequest={customRequest}
                            action="/"
                            beforeUpload={beforeUpload}
                        >
                            {logoAllUrl ? <img src={logoAllUrl} alt="logo" style={{ width: '100%' }} /> : uploadButton}
                        </Upload> 
                    </Col> 
                    </Row>
                 {info && <Form
                    name="form"
                    {...formItemLayout}
                    onFinish={onFinish}
                    initialValues={info}>
                     <Form.Item name="id" label="id" hidden>
                        <Input />
                    </Form.Item>
                    <Form.Item name="title" label="系统名称" rules={[ { required: true, message: '请输入系统名称' }]}>
                        <Input placeholder="请输入系统名称"/>
                    </Form.Item>
                    <Form.Item name="title_en" label="系统英文名称" rules={[ { required: true, message: '请输入系统英文名称' }]}>
                        <Input placeholder="请输入系统英文名称"/>
                    </Form.Item>
                    <Form.Item name="slogan" label="标语" rules={[ { required: true, message: '请输入标语' }]}>
                        <Input placeholder="请输入标语"/>
                    </Form.Item>
                    <Form.Item name="version" label="系统版本号" rules={[ { required: true, message: '请输入系统版本号' }]}>
                        <Input placeholder="请输入系统版本号"/>
                    </Form.Item>
                    <Form.Item name="iconfontProjectUrl" label="iconfont项目地址" rules={[ { required: true, message: '请输入iconfont项目地址' }]}>
                        <Input placeholder="请输入iconfont项目地址"/>
                    </Form.Item>
                    <Form.Item name="iconfontUrl" label="iconfont js在线地址" rules={[ { required: true, message: '请输入iconfont js在线地址' }]}>
                        <Input placeholder="请输入iconfont js在线地址"/>
                    </Form.Item>
                    <Form.Item  label="上次更新时间">
                        <span>{info?.updated_at}</span>
                    </Form.Item>
                    <Form.Item wrapperCol={{ span: 6, offset: 6 }}>
                        <Space>
                            <Button type="primary" htmlType="submit">保存</Button>
                            <Button onClick={closeBox}>关闭</Button>  
                        </Space>
                    </Form.Item>  
                </Form>}
              </Col>
            </Row>
        </Card>
    )
}

export default SysSettings